from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers
from goods.models import SKU
from goods.search_indexes import SKUIndex
from django_redis import get_redis_connection


class GoodsSerializers(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = '__all__'


class SKUIndexSerializers(HaystackSerializer):
    """SKU索引结果数据序列化器"""
    # 返回的商品数据对象指定返回字段内容
    object = GoodsSerializers(read_only=True)
    class Meta:
        index_classes = [SKUIndex]
        fields = ('text',)


class GoodsHistorySerializers(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):
        # 验证stu_id所对应的商品是否存在
        try:
            SKU.objects.get(id=attrs['sku_id'])
        except BaseException:
            raise serializers.ValidationError('商品不存在!')
        return attrs

    def create(self, validated_data):
        user = self.context['request'].user
        # 将sku_id保存到redis中
        # 建立缓存链接
        conn = get_redis_connection('history')
        # 先删除重复的商品数据
        conn.lrem('history_%s' % user.id, 0, validated_data['sku_id'])
        # 写入数据
        conn.lpush('history_%s' % user.id, validated_data['sku_id'])
        # 控制数量
        conn.ltrim('history_%s' % user.id, 0, 4)

        return validated_data